package com.jiesone.logger.distributecleaning.handler;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.jiesone.logger.distributecleaning.entity.ResponseData;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Description 功能描述：  验证响应的 token值是否合法  采用 springMVC
 * @Author tangsixiang@163.com
 * @DATE 2019/6/24 11:04
 * @Version 1.0
 **/
//@Component
@Slf4j
public class TokenHandler implements HandlerInterceptor {

    /***
     *  通过拦截请求方法 在此处判断 1、 token值是否有效
     *                            2、 请求连接是否有权限
     *
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        String token = request.getHeader("authorization");

        log.error("------------------进入拦截器数据-------------------------");
        return true;
    }

    //请求不通过，返回错误信息给客户端
    private void responseMessage(HttpServletResponse response, PrintWriter out, ResponseData responseData) throws Exception {
        response.setCharacterEncoding("utf-8");
        responseData = ResponseData.forbidden();
        response.setContentType("application/json; charset=utf-8");
        String json = new ObjectMapper().writeValueAsString(responseData);
        out.print(json);
        out.flush();
        out.close();
    }


}
